package com.sblab.appengine.dao.plain;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.sblab.appengine.dao.StadiumDao;
import com.sblab.appengine.domain.Stadium;

public class PlainStadiumDao implements StadiumDao {

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException ex) {
			// noop
		}
	}	
	
	/**
	 * Gets a connection
	 *  
	 * @return Connection object
	 * @throws SQLException if the connection cannot be established
	 */
	private Connection getConnection() throws SQLException {
		return DriverManager.getConnection("jdbc:mysql://1.234.91.91:3306/futsarang", "root", "secret");
	}
	
	/**
	 * Safely closes connection
	 * 
	 * @param connection Connection to close. Can be null.
	 */
	private void closeConnection(Connection connection) {
		if (connection == null) return;
		
		try {
			connection.close();
		} catch (SQLException ex) {
			// noop
		}
	}	

	public List<Stadium> findAll() {
		List<Stadium> result = new ArrayList<Stadium>();
		
		Connection connection = null;
		try {
			connection = getConnection();
			PreparedStatement statement = connection.prepareStatement("select * from Stadium");
			ResultSet resultSet = statement.executeQuery();
			while (resultSet.next()) {
				Stadium Stadium = new Stadium();
				Stadium.setId(resultSet.getInt("id"));
				Stadium.setName(resultSet.getString("name"));
				Stadium.setAddress(resultSet.getString("address"));
				result.add(Stadium);
			}
		} catch (SQLException ex) {
			ex.printStackTrace();
		} finally {
			closeConnection(connection);
		}
		
		return result;
	}
}
